import 'package:cult/function/widgets/custom_snackbar.dart';
import 'package:cult/function/widgets/report_dialog.dart';
import 'package:get/get.dart';
import '../../function/state/user_state.dart';
import '../../function/state/follow_state.dart';
import '../../function/state/like_state.dart';
import '../../function/state/post_state.dart';
import '../../function/state/single_chat_state.dart';
import '../../function/model/user_model.dart';
import '../../function/model/post_model.dart';
import '../../function/widgets/login_dialog_widget.dart';

/// 他人个人资料页面控制器
class OtherProfilePageController extends GetxController {
  final UserState _userState = Get.find<UserState>();
  final FollowState _followState = Get.find<FollowState>();
  final LikeState _likeState = Get.find<LikeState>();
  final PostState _postState = Get.find<PostState>();
  final SingleChatState _singleChatState = Get.find<SingleChatState>();

  // 目标用户
  final Rx<UserModel?> _targetUser = Rx<UserModel?>(null);

  // 当前选中的标签页
  final RxInt currentTabIndex = 0.obs;

  @override
  void onInit() {
    super.onInit();
    _initializeTargetUser();
  }

  /// 初始化目标用户
  void _initializeTargetUser() {
    final arguments = Get.arguments;
    if (arguments is UserModel) {
      _targetUser.value = arguments;
    } else if (arguments is String) {
      // 如果传入的是用户ID
      final user = _userState.getUserById(arguments);
      _targetUser.value = user;
    }
  }

  /// 获取目标用户
  UserModel? get targetUser => _targetUser.value;

  /// 获取当前用户
  UserModel? get currentUser => _userState.currentUser;

  /// 是否已登录
  bool get isLoggedIn => _userState.isLoggedIn;

  /// 是否是自己
  bool get isSelf {
    if (!isLoggedIn || targetUser == null) return false;
    return currentUser!.id == targetUser!.id;
  }

  /// 获取关注数量
  int get followingCount {
    if (targetUser == null) return 0;
    return _followState.allFollows
        .where((follow) => follow.followerId == targetUser!.id)
        .length;
  }

  /// 获取粉丝数量
  int get followersCount {
    if (targetUser == null) return 0;
    return _followState.allFollows
        .where((follow) => follow.followingId == targetUser!.id)
        .length;
  }

  /// 获取点赞数量（用户收获的点赞数）
  int get likesReceivedCount {
    if (targetUser == null) return 0;
    return _likeState.getUserTotalLikes(targetUser!.id);
  }

  /// 是否已关注该用户
  bool get isFollowing {
    if (!isLoggedIn || targetUser == null) return false;
    return _followState.isFollowing(targetUser!.id);
  }

  /// 获取用户发布的帖子（按日期分组）
  Map<String, List<PostModel>> get userPostsByDate {
    if (targetUser == null) return {};
    final posts =
        _postState.allPosts
            .where((post) => post.userId == targetUser!.id)
            .toList()
          ..sort((a, b) => b.publishTime.compareTo(a.publishTime));

    return _groupPostsByDate(posts);
  }

  /// 获取用户点赞的帖子（按日期分组）
  Map<String, List<PostModel>> get userLikedPostsByDate {
    if (targetUser == null) return {};
    final likedPostIds =
        _likeState.allLikes
            .where((like) => like.userId == targetUser!.id)
            .map((like) => like.postId)
            .toList();
    final posts =
        _postState.allPosts
            .where((post) => likedPostIds.contains(post.id))
            .toList()
          ..sort((a, b) => b.publishTime.compareTo(a.publishTime));

    return _groupPostsByDate(posts);
  }

  /// 按日期分组帖子
  Map<String, List<PostModel>> _groupPostsByDate(List<PostModel> posts) {
    final Map<String, List<PostModel>> groupedPosts = {};

    for (final post in posts) {
      final dateKey = _formatDateKey(post.publishTime);
      if (!groupedPosts.containsKey(dateKey)) {
        groupedPosts[dateKey] = [];
      }
      groupedPosts[dateKey]!.add(post);
    }

    return groupedPosts;
  }

  /// 格式化日期键
  String _formatDateKey(DateTime date) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(Duration(days: 1));
    final postDate = DateTime(date.year, date.month, date.day);

    if (postDate == today) {
      return 'Today';
    } else if (postDate == yesterday) {
      return 'Yesterday';
    } else {
      return _formatDateWithMonthAbbreviation(date);
    }
  }

  /// 格式化日期为月份缩写形式
  String _formatDateWithMonthAbbreviation(DateTime date) {
    const monthAbbreviations = [
      'Jan.',
      'Feb.',
      'Mar.',
      'Apr.',
      'May',
      'Jun.',
      'Jul.',
      'Aug.',
      'Sep.',
      'Oct.',
      'Nov.',
      'Dec.',
    ];

    final monthAbbr = monthAbbreviations[date.month - 1];
    return '$monthAbbr ${date.day}';
  }

  /// 格式化时间显示
  String formatTime(DateTime dateTime) {
    final hour = dateTime.hour.toString().padLeft(2, '0');
    final minute = dateTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 切换标签页
  void switchTab(int index) {
    currentTabIndex.value = index;
  }

  /// 返回上一页
  void goBack() {
    Get.back();
  }

  /// 举报用户
  void reportUser() {
    ReportDialogUtils.showReportDialog(
      onReportSubmitted: (reportType) {
        Get.back();
      },
    );
  }

  /// 关注/取消关注用户
  void toggleFollow() {
    if (!isLoggedIn) {
      LoginDialogUtils.showLoginDialog();
      return;
    }

    if (targetUser == null) return;

    if (isFollowing) {
      _followState.unfollowUser(targetUser!.id);
      CustomSnackBar.success('You have unfollowed ${targetUser!.nickname}');
    } else {
      _followState.followUser(targetUser!.id);
      CustomSnackBar.success('You are now following ${targetUser!.nickname}');
    }
  }

  /// 开始聊天
  void startChat() {
    if (!isLoggedIn) {
      LoginDialogUtils.showLoginDialog();
      return;
    }

    if (targetUser == null) return;

    // 检查是否已有对话
    final existingChat = _singleChatState.getChatWithUser(targetUser!.id);

    if (existingChat != null) {
      // 已有对话，直接跳转
      Get.toNamed('/single-chat', arguments: existingChat);
    } else {
      // 创建新对话并跳转
      final newChat = _singleChatState.ensureChatWithUser(targetUser!.id);
      Get.toNamed('/single-chat', arguments: newChat);
    }
  }

  /// 播放视频
  void playVideo(PostModel post) {
    if (post.resourceType == ResourceType.video) {
      Get.toNamed('/video-player', arguments: post);
    }
  }

  /// 跳转到帖子详情页面
  void goToPostDetail(PostModel post) {
    Get.toNamed('/post-detail', arguments: post);
  }
}
